#!/bin/bash
BINPATH='/opt/.airship/airship-agent'

function make_service() {
  echo "create airship-box-agent service..."
  ID=$1
  SupplierID=""
  arg_sid=""
  if [ -n "${SupplierID}" ];then
    arg_sid="-s ${SupplierID}"
  fi
  PPApiServer=""
  api_server_arg=""
  if [ -n  "${PPApiServer}" ];then
    api_server_arg="--api-server '"${PPApiServer}"'"
  fi
  cat > /usr/lib/systemd/system/airship-box-agent.service << EOF
[Unit]
Description=PPIO Push System

[Service]
Environment=PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
Environment=AIRSHIP_WORKSPACE=/opt/.airship
ExecStart=/opt/.airship/airship-agent serve --class box ${arg_sid} ${api_server_arg} --supplier-device-id $ID --daemon=false
User=root
Group=root
Restart=always
KillMode=process

[Install]
WantedBy=multi-user.target
EOF
  systemctl enable airship-box-agent
  systemctl restart airship-box-agent
}

while true; do
  SN=$(cat /etc/device_sn)
  if [ -z "$SN" ]; then 
    echo "error: supplier device id (SN) is not provided"
    sleep 60
    continue
  fi
  echo "use SN: $SN"

  need_download=0
  if ! [ -f "${BINPATH}" ];then
    need_download=1
  else
    filesize=$(stat -c "%s" "${BINPATH}")
    if [[ "${filesize}" -eq "0" ]];then
      need_download=1
    else
      if ! ${BINPATH} --version >/dev/null 2>&1; then
        need_download=1
      fi
    fi
  fi

  if [[ "${need_download}" == "0" ]]; then
    echo "airship-agent is already installed"
    sleep 3600
    continue
  fi
  
  echo "download airship-agent..."
  mkdir -p $(dirname $BINPATH)
  if ! curl -sSL -o $BINPATH  'http://pi-ops-1312767721.cos.ap-shanghai.myqcloud.com/airship/airship-agent-linux-arm64-latest'; then
    
  echo "## generate by pp
nameserver 114.114.114.114
nameserver 223.5.5.5
nameserver 119.29.29.29" > /etc/resolv.conf
    
    sleep 1
    if ! curl -sSL -o $BINPATH  'http://pi-ops-1312767721.cos.ap-shanghai.myqcloud.com/airship/airship-agent-linux-arm64-latest'; then
      echo "download airship-agent failed"
      rm -f "${BINPATH}"
      sleep 30
      continue
    fi
  fi

  chmod a+x $BINPATH
  if $BINPATH --version 2>/dev/null; then
    make_service $SN
  else
    echo "failed to install airship-agent binary..."
    rm -f "${BINPATH}"
    sleep 30
  fi
  
done


